<template>
  <div class="chart" ref="chartRef"></div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import http from '../http.js'

const chartRef = ref<HTMLElement | null>(null)

onMounted(async () => {
  // 1. 请求数据
  const res = await http.get('/trend.json')
  const map = res.map
  const months = res.common.month

  // 2. 组装 legend 和 series
  const legendData = map.data.map(item => item.name)
  const series = map.data.map(item => ({
    name: item.name,
    type: 'line',
    stack: '总量',
    areaStyle: { opacity: 0.8 },
    emphasis: { focus: 'series' },
    data: item.data.map(Number)
  }))

  // 3. 组装 option
  const option = {
    title: {
      text: '| ' + map.title,
      textStyle: {
        color: '#fff',
        fontSize: 14,
        fontWeight: 'normal'
      },
      left: '2%',
      top: '2%'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: { backgroundColor: '#6a7985' }
      }
    },
    legend: {
      data: legendData,
      textStyle: { color: '#fff', fontSize: 12 },
      top: '15%',
      left: '2%',
      itemWidth: 15,
      itemHeight: 10,
      itemGap: 10,
      orient: 'horizontal'
    },
    grid: {
      left: '5%',
      right: '8%',
      top: '32%',
      bottom: '12%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: months,
      axisLabel: { color: '#fff' }
    },
    yAxis: {
      type: 'value',
      axisLabel: { color: '#fff' }
    },
    series
  }

  // 4. 渲染图表
  const myChart = echarts.init(chartRef.value!)
  myChart.setOption(option)
  window.addEventListener('resize', () => myChart.resize())
})
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
  padding: 10px;
}
</style>
